// 有序数组的平方
// https://leetcode.cn/problems/squares-of-a-sorted-array/solutions/447736/you-xu-shu-zu-de-ping-fang-by-leetcode-solution/

/**
 * @param {number[]} nums
 * @return {number[]}
 */
var sortedSquares = function (nums) {
    let ret = [];
    const numsCount = nums.length;

    const splitIndex = nums.findIndex((n) => n >= 0);

    let leftIndex = splitIndex === -1 ? numsCount - 1 : splitIndex - 1;
    let rightIndex = splitIndex === -1 ? numsCount : splitIndex;

    while (leftIndex >= 0 || rightIndex < numsCount) {
        let left = null;
        let right = null;

        if (leftIndex >= 0) {
            left = Math.abs(nums[leftIndex]);
        }

        if (rightIndex < numsCount) {
            right = Math.abs(nums[rightIndex]);
        }

        let current = null;

        if (left === null) {
            current = right;
            rightIndex++;
        } else if (right === null) {
            current = left;
            leftIndex--;
        } else if (left < right) {
            current = left;
            leftIndex--;
        } else {
            current = right;
            rightIndex++;
        }

        ret.push(current ** 2);
    }

    console.log(`ret is ${JSON.stringify(ret)}`);
    return ret;
};

sortedSquares([-4, -1, 0, 3, 10]); // [-4,-1,0,3,10]
sortedSquares([-7, -3, 2, 3, 11]); // [4,9,9,49,121]
sortedSquares([-1]); // [1]
